using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace GardeningSkeleton.Platform.SkillSpace
{
    /// <summary>
    /// 闪电链 
    /// </summary>
    public class NearlySkillSelector : ISkillSelector
    {

        public HashSet<Transform> SelectTarget(SkillData skillData, Transform skillPrefab)
        {
            Collider2D[] colliders = Physics2D.OverlapCircleAll(skillPrefab.transform.position, skillData.range, skillData.attackTargetLayers);

            var taragets = new HashSet<Transform>();

            // 找到离上次目标最近的敌人
            Collider2D closestTarget = null;
            float closestDistance = float.MaxValue;
            foreach (var collider in colliders)
            {
                // 忽略上次选择的敌人
                if (collider.transform == skillData.lastTarget) continue;

                float distance = Vector2.Distance(collider.transform.position, skillPrefab.transform.position);
                if (distance < closestDistance)
                {
                    closestTarget = collider;
                    closestDistance = distance;
                }
            }

            if (closestTarget != null)
            {
                //最近的和上一次相同，说明只有一个敌人
                if (skillData.lastTarget == null || skillData.lastTarget != closestTarget.transform)
                {
                    skillData.lastTarget = closestTarget.transform;
                    taragets.Add(closestTarget.transform);
                }
            }

            skillData.attackTargets = taragets;
            return taragets;
        }
    }
}